package com.kgc.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 请求，响应编码过滤器
 */
@WebFilter(filterName = "EncodingFilter", value = "/*", initParams = @WebInitParam(name = "encoding", value = "UTF-8"))
public class EncodingFilter implements Filter {


    // 静态资源白名单 (处理后缀)
    private List<String> staticTypes = Arrays
            .asList(".css", ".js", ".ico", ".png", ".jpg", ".bmp", ".svg",".json",".otf","eot",".ttf",".woff",".woff2",".less",".scss",".txt",".jsp");

    /**
     * 请求过滤器编码
     * 默认 UTF-8
     */
    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding = filterConfig.getInitParameter("encoding");
        if (encoding != null) {
            this.encoding = encoding;
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // 处理请求编码问题
        request.setCharacterEncoding(this.encoding);

        // 响应编码处理
        String requestURI = request.getRequestURI();
        for (String staticType : staticTypes) {
            if (requestURI.endsWith(staticType)) {
                // 静态资源不用处理编码
                chain.doFilter(request, response);
                return;
            }
        }
        // 响应编码 text编码  不能处理静态资源
        response.setContentType("text/html;charset=" + this.encoding);
        chain.doFilter(request, response);
    }
}
